/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.source.network;

import android.content.Intent;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.logos.common.source.network.callback.HttpRespondResultCallBack;
import com.logos.common.source.network.entity.BaseNetEntity;
import com.logos.common.source.network.entity.FailedNetEntity;
import com.logos.tool.ActivityManagerUtils;
import com.logos.tool.log.LogUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Young Ken
 */
public class BaseNetWorkSubscriber<T> implements Observer<T> {

    private HttpRespondResultCallBack mCallback;
    private static final String TAG = "BaseNetWorkSubscriber";

    public BaseNetWorkSubscriber(HttpRespondResultCallBack callback) {

        mCallback = callback;
    }

    @Override
    public void onError(final Throwable throwable) {
        ExceptionHandle.ResponseThrowable failed = ExceptionHandle
                .handleException(throwable);
        FailedNetEntity entity = new FailedNetEntity(failed.code, failed.message);
        mCallback.onFailure(throwable, entity);
        LogUtil.error("BaseNetWorkSubscriberError", "Code: " + failed.code
                + " Message: " + LogUtil.getStackTrace(throwable));
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onSubscribe(Disposable disposable) {
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onNext(T entity) {
        if (entity != null) {
            if (entity instanceof BaseNetEntity) {
                int code = ((BaseNetEntity) entity).getCode();
                String message = ((BaseNetEntity) entity).getMessage();

                //针对返回code码进行进一步封装
                if (code != 1) {
                    //token失效
//                    if (code==900){
//                        // 带请求码跳转，在onActivityResult中返回数据
//                        ActivityManagerUtils.getInstance().finishAllActivity();
//                        ARouter.getInstance().build("/login/LoginActivity").navigation();
//                    }else {
                        onError(new BaseThrowable(code, message));
//                    }

                } else {
                    mCallback.onSuccess(entity);
                }
            }

        }
    }
}
